package com.gzz.orchid.common.boot.mybatis.lambda;

import com.gzz.orchid.common.core.support.R;
import com.gzz.orchid.common.core.util.StringUtil;

import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;

/**
 *
 * @author higmd
 */
public class LambdaUtil {

    /**
     * 获取属性名
     */
    public static <T> String getPropertyName(SFunction<T, R> func) throws Exception{
        String implMethodName = getLambda(func).getImplMethodName();
        if(implMethodName.startsWith("get")){
            implMethodName = implMethodName.substring(3);
        }else if(implMethodName.startsWith("is")){
            implMethodName = implMethodName.substring(2);
        }
        return StringUtil.camelToSnake(implMethodName);
    }

    /**
     * 获取属性类型
     */
    public static <T>Class<?> getPropertyType(SFunction<T,R> func)throws Exception{
        String instantiatedMethodType = getLambda(func).getInstantiatedMethodType();
        String instantiatedType = instantiatedMethodType
                .substring(2, instantiatedMethodType.indexOf(';'))
                .replace('/', '.');
        return Class.class.forName(instantiatedType);
    }

    /**
     * 获取实例化类
     */
    private static <T>SerializedLambda getLambda(SFunction<T,R> func)throws Exception{
        Method writeReplace = func.getClass().getDeclaredMethod("writeReplace");
        writeReplace.setAccessible(true);
        // SerializedLambda lambda = (SerializedLambda) writeReplace.invoke(func);
       return (SerializedLambda) writeReplace.invoke(func);
    }
}
